package app.biz.config;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by gu on 2017/2/18.
 */
@Configuration
public class MongoDataSource {

    private static final Logger logger = LoggerFactory.getLogger(MongoDataSource.class);
    static MongoClient mongoClient;

    @Value("${mongo.url}")
    private String dbUrl;
    @Value("${mongo.ecgdb:#{ecg}}")
    private String dbName;

    public void setDbUrl(String dbUrl) {
		this.dbUrl = dbUrl;
	}

	public void setDbName(String dbName) {
		this.dbName = dbName;
	}

	@Bean
	public MongoDatabase getDB(){
        return getDB(dbName);
    }

	public MongoDatabase getDB(String dbName){
        if(mongoClient==null) {
            MongoClientURI connectionString = new MongoClientURI(dbUrl);
            mongoClient = new MongoClient(connectionString);
        }
        return mongoClient.getDatabase(dbName);
    }

    public  MongoCollection<Document> getCollecton(String collectionName) {
        return getDB().getCollection(collectionName);
    }
}
